﻿using ADOX;
using nhCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace nhCore
{
    public class YunLinkIO : IO
    {
        public static string Sn { get; set; }
        public static string Pwd { get; set; }
        private static AutoResetEvent AutoEvent { get; set; } = new AutoResetEvent(false);

        private object ReturnData { get; set; }

        public YunLinkIO(string sn, string pwd)
        {
            Sn = sn;
            Pwd = pwd;
        }

        public override bool Close()
        {
            IOListener.DisConnected(this, this);
            return true;
        }

        public override bool Open(bool asyncComm = false)
        {
            //HttpHelper.GetAllRealTimeDataAsync(Sn, Pwd, OnFirstData);
            HttpHelper.GetDataAsync<BootAllRealTimeData>($"http://yunlink.027010.cn/OpenAPI/GetAllReal?sn={Sn}&pwd={Pwd}", OnFirstData);
            return true;
        }

        /// <summary>
        /// 首次调用返回
        /// </summary>
        /// <param name="httpAllRealTimeResult"></param>
        public void OnFirstData(BootAllRealTimeData httpAllRealTimeResult)
        {
            List<RealTimeDatas> listRtDatas = httpAllRealTimeResult.Datas;
            if (listRtDatas.Count > 0)
            {
                bool has = false;
                //判断是否有ID在sensors表中，并作出提示
                DicEnvStat dicEnvStat = DicEnvStat.Singleton;
                foreach (RealTimeDatas data in listRtDatas)
                {
                    var re = dicEnvStat.EnvStats.Values.Where(x => x.Id == data.ID);
                    if (!re.Any())//不包含任何元素
                    {
                        IOListener.Error($"{data.Device} ID:{data.ID} 在本机数据库中没有对应设备，请重新配置。");
                    }
                    else
                    {
                        has = true;
                    }
                }
                if (has)
                {
                    IsOpened = true;
                    IOListener.Connected(this, this);
                }
            }
            else
            {
                IsOpened = false;
                Close();
                string msg = httpAllRealTimeResult.State == 0 ? "API未开通，请联系管理员。" : httpAllRealTimeResult.Message;
                IOListener.Error(msg);
            }
        }

        public override bool Send(object client, in object bytes)
        {
            byte code;
            string writeData;
            (code, writeData) = ((byte, string))bytes;
            BootOneRealTimeData bootOneRealTimeData = new BootOneRealTimeData();
            bootOneRealTimeData.GetType();
            if (code == 0x04)
            {
                HttpHelper.GetDataAsync<BootOneRealTimeData>(writeData, OnData);
            }
            else if (code == 0x41)
            {

                HttpHelper.GetDataAsync<BootHistoryData>(writeData, OnData);
            }
            else
            {
                return false;
            }
            return true;
        }

        public override object SendAccept(object client, object writeData)
        {
            object ret = null;
            if (Send(client, writeData))
            {
                AutoEvent.Reset();
                if (AutoEvent.WaitOne(20000))
                {
                    ret = ReturnData;
                }
                else
                {
                    Debug.WriteLine($"\t\t\t\t\t\t\t\t 云平台请求帧，没有等到回应。");
                }
            }

            return ret;
        }

        /// <summary>
        /// http数据返回
        /// </summary>
        /// <typeparam name="T">返回的数据类型</typeparam>
        /// <param name="httpResult">返回的数据</param>
        public void OnData<T>(T httpResult)
        {
            ReturnData = httpResult;
            AutoEvent.Set();
        }
    }
}
